package handler

import (
	"2301a/goods/api/request"
	"2301a/goods/internal/dao"
	"2301a/goods/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddComment(c *gin.Context) {
	var req request.AddCommentReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	dao.Create(&model.Comment{
		UserId:  userId,
		GoodsId: req.GoodsId,
		Message: req.Message,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "发表评论成功",
		"data": true,
	})
}

func ListComment(c *gin.Context) {
	var req request.ListCommentReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	var list []model.Comment
	dao.GetListByFields(&model.Comment{
		UserId:  userId,
		Message: req.Message,
	}, &list)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "发表评列表成功",
		"data": list,
	})
}

func DetailsComment(c *gin.Context) {
	var req request.DetailsCommentReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	var comment model.Comment
	dao.GetOneById(req.Id, &comment)
	if comment.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "发表评论失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "发表评详情成功",
		"data": comment,
	})
}

func RemoveComment(c *gin.Context) {
	var req request.RemoveCommentReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	dao.Delete(&model.Comment{Id: req.Id})

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "删除评详成功",
		"data": true,
	})
}
